var express = require('express');
var router = express.Router();
var md5 = require('md5');
var mysql = require('mysql');

var resData = null;

var db = mysql.createPool({ host: 'localhost', user: 'root', password: '', database: 'blog' });

/* GET users listing. */
router.get('/', function(req, res, next) {
    res.send('respond with a resource');
});

router.use(function(req, res, next) {
    res.header("Access-Control-Allow-Origin", "*");
    res.header("Access-Control-Allow-Headers", "X-Requested-With");
    res.header("Access-Control-Allow-Methods", "PUT,POST,GET,DELETE,OPTIONS");
    res.header("Content-Type", "application/json;charset=utf-8");
    next();
})

router.use(function(req, res, next) {
    resData = {
        code: 0,
        message: ''
    };
    next()
})

router.post('/post',function(req, res, next){
    console.log(req.body)
    db.query(`SELECT username,email FROM zq_user`, function(err, data) {
        console.log(data)
        res.json(data);
    })
})


router.post('/info', function(req, res, next) {
    var username = req.body.userName;
    var password = req.body.password;
    var email = req.body.email;
    password = md5(password);
    console.log(req.body)
    db.query(`SELECT username,email FROM zq_user WHERE username='${username}'`, function(err, data) {
        if(err){
            resData.message = '数据库开小差';
            resData.code = '-1';
            res.json(resData);
        }

        if(data.length){
            resData.message = '该用户名已存在';
            resData.code = '-2';
            res.json(resData);
        }else{

            db.query(`INSERT INTO zq_user(username,password,email) VALUES('${username}','${password}','${email}')`,function(err,data){
                if(err){
                    resData.message = '数据库开小差';
                    resData.code = '-3';
                    res.json(resData);
                }else{
                    resData.message = '注册成功';
                    resData.code = '0';
                    res.json(resData);
                }
                console.log(data)
            })
        }
    })
});

router.get('/login', function(req, res, next) {
    res.send('respond with a login');
});

router.get('/loginOut', function(req, res, next) {
    res.send('respond with a loginOut');
});

module.exports = router;